import React, { useRef, useState } from "react";
import WithTreeList from "@/biz-components/hoc-form/with-tree-list";
import { onFieldValueChange, onFormMount } from "@formily/core";
import api, { categoryCreate, categoryUpdate, categoryDelete } from './services';
import ModalRenderForm from "@/biz-components/hoc-form/with-list/modal-Render-form";
import { Form } from "@formily/core/esm/models";

import './index.less';
import { getSubmitFormValues } from "@ey-utils/utils/formily-utils/getSubmitFormValues";
import { message } from "antd";
export interface WithTreeTableProps {

}

const codePattern = /^[a-zA-Z0-9]*$/;

const ArchivesCategory: React.FC<WithTreeTableProps> = () => {
    const [visible, setVisible] = useState(false);
    const [loading, setLoading] = useState(false);
    const [editData, setEditData] = useState<any>();
    const [modalType, setModalType] = useState<'create' | 'edit'>('create');
    const [currentNode, setCurrentNode] = useState<any>();
    const [refresh, setRefresh] = useState(false);

    const modalFormRef = useRef<Form<any>>();

    const createEditModal = () => {
        return (
            <ModalRenderForm
                width={650}
                visible={visible}
                title={`档案分类${modalType === 'create' ? '新增' : '编辑'}`}
                modalCode="ArcvCtgry_CUD"
                formConfigs={{
                    effects: (form) => {
                        modalFormRef.current = form;

                        onFormMount((f) => {
                            f.query('code').take((field) => {
                                field.setValidator({
                                    validator: () => {
                                        if(!codePattern.test(field.value)) {
                                            return "编码只能为数字或字母";
                                        }
                                        return "";
                                    },
                                });
                            })
                        })

                    }
                }}
                events={{
                    handleOk: async () => {
                        const values = await getSubmitFormValues(modalFormRef.current as Form<any>);

                        if (modalType === 'create') {
                            categoryCreate({
                                ...values,
                                parentCode: currentNode.code,
                                pageCode: 'ArcvCtgry_CUD'
                            }).then((res: any) => {
                                if (res.success) {
                                    message.success('新增成功');
                                    setRefresh(!refresh);
                                    modalFormRef.current?.reset()
                                    setVisible(false);
                                }
                            })
                        } else {
                            categoryUpdate({
                                ...values,
                                id: editData.id,
                                parentCode: currentNode?.code,
                                pageCode: 'ArcvCtgry_CUD'
                            }).then((res: any) => {
                                if (res.success) {
                                    message.success('编辑成功');
                                    setRefresh(!refresh);
                                    setVisible(false);
                                }
                            })
                        }
                    }
                }}
                onCancel={() => {
                    modalFormRef.current?.reset();
                    setVisible(false);
                }}
            />
        )
    }

    return (
        <div className="archives-category">
            <WithTreeList
                async={false}
                canSearch={false}
                searchCode="ArcvCtgry_L"
                modalCode="ArcvCtgry_CUD"
                noModal={false}
                noQueryKeys={true}
                nodeKeys={['code']}
                selectNode={(node: any) => {
                    setCurrentNode(node);
                }}
                treeParams={{
                    pageCode: "ArcvCtgry_L",
                    parentCode: "0"
                }}
                keyName={"code"}
                titleName={"name"}
                // paramsMap={['parentCode']}
                refreshFlag={refresh}
                pageApi={api.page}
                url={api.tree}
                method={"POST"}
                events={{
                    buttonsEvents: {
                        search: () => {
                            console.log('search')
                        },
                        handleCreate: () => {
                            if (!currentNode) {
                                message.error('请先选择父节点');
                                return;
                            }

                            setModalType('create');
                            setVisible(true);
                        }
                    },
                    tableButtonsEvents: {
                        handleEdit: (key: string, row: any) => {
                            const { id, ...data } = row;
                            modalFormRef.current?.setValues({ ...data });
                            setModalType('edit');
                            setVisible(true);
                            setEditData(row);
                        },
                        handleDelete: (key: string, row: any) => {
                            debugger
                            categoryDelete({
                                id: row.id,
                                pageCode: 'ArcvCtgry_CUD'
                            }).then((res: any) => {
                                if (res.success) {
                                    message.success('删除成功');
                                    setRefresh(!refresh);
                                }
                            })
                        }
                    }
                }}
                modalformConfigs={(params: any) => {
                    onFormMount((form) => {
                        // if (params.treeNode.current) {
                        //     form.getFieldState('nodeType', (field) => {
                        //         field.value = params.treeNode.current.nodeType
                        //     })
                        //     form.getFieldState('formerNode', (field) => {
                        //         field.disabled = true
                        //         field.value = params.treeNode.current.code
                        //     })
                        // }
                    })
                    onFieldValueChange('nodeType', (field) => {
                        console.log(params)
                    })
                }}
            />
            { createEditModal() }
        </div>
    )
}

export default ArchivesCategory;
